package myJs.login

import myJs.CpLayer.{loadComplete, startLoad}
import myJs._
import myJs.api.Api
import myJs.assets.assetsCss
import myJs.cps._
import myJs.myPkg.reactHookForm._
import org.scalajs.dom.{URLSearchParams, document, window}
import slinky.core.FunctionalComponent
import slinky.core.annotations.react
import slinky.core.facade.{Fragment, ReactElement}
import slinky.core.facade.Hooks.{useEffect, useState}
import slinky.web.html._
import typings.csstype.csstypeStrings
import myJs.myPkg.jquery._
import myJs.Implicits._
import myJs.myPkg.{BackstretchOptions, ReactRouterDOM}
import myJs.user.home.Home
import org.scalajs.dom.window.localStorage
import shared.pojo._
import shared.pojo.Pojo._

import scala.scalajs.js
import scala.scalajs.js.JSConverters._
import scala.scalajs.js.JSON
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import myJs.Implicits._
import myJs.tool.Tool

@react object Cp {

  type Props = Unit

  private val css = List(
    assetsCss.Layer,
    assetsCss.Sweetalert,
    assetsCss.BootstrapMin,
    assetsCss.BootstrapThemeMin,
    assetsCss.Doc,
    assetsCss.BootstrapDatepicker3,
    //    assetsCss.FontAwesomeMin,
    assetsCss.FontAwesomeMin,
    assetsCss.Components,
    assetsCss.BootstrapTable,
    assetsCss.Nprogress,
    assetsCss.TableFilter,
    assetsCss.Login5Min
  )

  private val css2 = assetsCss.My

  val component = FunctionalComponent[Props] { props =>
    val useForm = ReactHookForm.useForm(UseFormOptions(mode = "onChange"))
    val navigate = ReactRouterDOM.useNavigate()
    val location = ReactRouterDOM.useLocation()
    val searchParams = new URLSearchParams(location.search)

    val (name, setName) = useState("")
    val (password, setPassword) = useState("")
    val (info, setInfo) = useState(span(): ReactElement)
    val (errorClass, setErrorClass) = useState("")

    object FTool {

      def nameChange = (v: String) => {
        setName(v)
      }

      def passwordChange = (v: String) => {
        setPassword(v)
      }

      def formSubmit = useForm.handleSubmit((data: js.Dictionary[js.Any]) => {
        println(JSON.stringify(data))
        FTool.login()
      })

      def login = () => {
        val request = Pojo.Login.Request(name = name, password = password)
        Api.login(request).map { response =>
          if (response.valid) {
            if (response.activated) {
              localStorage.setItem("account", name)
              val role = response.role
              localStorage.setItem("role", role)
              localStorage.setItem("token", response.token)
              Role.withNameInsensitive(role) match {
                case Role.Admin => navigate(MyPage.admin.limitManage.navigatePath)
                case Role.User =>
                  localStorage.setItem("user_id", response.id.toString)
                  navigate(Home.navigatePath)
              }
            } else {
              val info = Fragment(
                "账户未激活，请前往 ",
                a(
                  href := s"${MyPage.registerActive.absolutePath}?email=${response.email}",
                  target := "_blank",
                  "激活"
                ),
                " !"
              )(): ReactElement
              setInfo(info)
              setErrorClass(response.errorClass)
            }
          } else {
            setInfo(span("用户名或密码错误!")())
            setErrorClass(response.errorClass)
          }
        }
        ()
      }

    }

    useEffect(
      () => {
        if (location.state != null) {
          val state = location.state.toJDJAn
          val message = state.myGet("message")
          val errorClass = state.myGet("errorClass")
          setInfo(message)
          setErrorClass(errorClass)
        }
      },
      List()
    )

    useEffect(
      () => {
        startLoad
        document.title = s"登录-LiveForest"
        loadComplete
      },
      List()
    )

    useEffect(
      () => {
        val images = List("login_3.jpg", "login_2.jpg", "login_1.jpg").map { name =>
          s"${Api.images}/${name}"
        }.toJSArray
        $(".login-bg")
          .backstretch(images = images, options = BackstretchOptions(fade = 1e3, duration = 8e3))
      },
      List()
    )

    div(
      className := "login loginHome",
      div(
        className := "user-login-5",
        div(
          className := "row bs-reset",
          div(
            className := "col-md-6 login-container bs-reset",
            TitleInfoCp(),
            div(
              className := "login-content",
              div(
                className := "register",
                h2(className := "page-heading", style := Style(fontSize = 25), "登录"),
                form(
                  style := Style(maxWidth = 320),
                  className := "registration-form",
                  onSubmit := FTool.formSubmit,
                  span(style := Style(lineHeight = "35px"), className := s"${errorClass}", info),
                  InputIconCp(
                    useForm = useForm,
                    name = "name",
                    value = name,
                    onChange = FTool.nameChange,
                    placeHolder = "用户名/邮箱/手机",
                    icon = "user"
                  ),
                  InputIconCp(
                    useForm = useForm,
                    name = "password",
                    value = password,
                    onChange = FTool.passwordChange,
                    placeHolder = "密码",
                    icon = "key",
                    `type` = "password",
                    registerOptions = RegisterOptions(
                      maxLength = 30
                    )
                  ),
                  div(
                    className := "actions",
                    button(
                      style := Style(width = "100%"),
                      `type` := "submit",
                      className := "btn btn-primary btn-lg",
                      s" 登录"
                    )
                  ),
                  div(
                    style := Style(marginTop = 10),
                    className := "form-group",
                    a(href := s"${MyPage.register.absolutePath}", target := "_blank", "立即注册"),
                    a(
                      href := s"${MyPage.recoverPassword.absolutePath}",
                      target := "_blank",
                      style := Style(position = csstypeStrings.relative, left = 200),
                      "忘记密码？"
                    )
                  )
                )
              )
            ),
            div(
              className := "login-footer",
              div(
                className := "row bs-reset",
                div(
                  className := "col-xs-12 bs-reset",
                  div(
                    className := "login-copyright text-right",
                    p(style := Style(color = "black"), "版权所有2018 深圳市绘云生物科技有限公司 All Rights Reserved")
                  )
                )
              )
            )
          ),
          div(className := "col-md-6 bs-reset", div(className := "login-bg"))
        )
      )
    )
  }

}
